import {Component} from 'react';
import React from 'react';
import {connect} from 'umi';

import HighPerformTable from '@/components/HighPerformTableSpecially';
// import KeywordFilterSearch from '@/components/KeywordFilterSearch';
import {Button, Input, message, Select} from 'antd';
import {PlusOutlined} from '@ant-design/icons';
import APIS from '@/apis';
import SearchAbleSelect from '@/components/SearchAbleSelect';
import CustomCascader from '@/components/CustomCascader/CustomCascader';
import {values} from 'lodash';

class ClassManagerPage extends Component<any, any> {
  actionRef: any;

  searchMajor: SearchAbleSelect | undefined;
  searchCollage: SearchAbleSelect | undefined;

  constructor(props: any) {
    super(props);
    this.state = {
      schoolId: 0,
      filterSchoolId: 0,
      collageId: 0,
      filterCollageId: 0,
      majorId: 0,
      filterMajorId: 0,
    }
  }

  componentDidMount() {
  }

  private filterId?: any = -1;
  private schoolId?: any = -1;
  private collegeId?: any = -1;

  handleChangeFilter(values: any) {
    if (values[0]) {
      //学校
      this.schoolId = values[0];
      if (!values[1]) {
        this.collegeId = -1;
        this.filterId = -1;
      }
    }
    if (values[1]) {
      //专业
      this.collegeId = values[1];
      if (!values[2]) {
        this.filterId = -1;
      }
    }
    if (values[2]) {
      //专业
      this.filterId = values[2];
    }
    this.actionRef.reload();
  }


  clomns: any = [

    {
      title: '班级',
      dataIndex: 'classIndex',
      rules: [
        {
          required: true,
          message: '规则名称为必填项',

        },
      ],
      renderFormItem: (item: any, config: any, form: any) => (
        <Input
          placeholder="请输入班级，如“1603”"
          type="number"
        />
      ),
      renderText: (val: string, recode: any) => (
        <span>{`${recode.grade}级${recode.classIndex}班`}</span>
      ),
    },
    {
      title: '年级',
      dataIndex: 'grade',
      hideInTable: true,
      renderFormItem: (item: any, config: any, form: any) => (
        <Input
          placeholder="请输入年级，如“2016”"
          type="number"
        />
      ),
      rules: [
        {
          required: true,
          message: '规则名称为必填项',
        }
      ],
    },
    {
      title: '学校',
      dataIndex: 'school',
      hideColumn: true,
      renderText: (val: string, recode: any) => (
        <span>{recode?.majorInfo ? recode.majorInfo.majorName : ''}</span>
      ),
      renderFormItem: (item: any, config: any, form: any) => (
        <SearchAbleSelect
          searchData={async (key) => {
            var datas: Array<any> = await APIS.OrgsAPI.SearchGetSchoolList({current: 1, pageSize: 9999});
            return Promise.resolve(
              datas?.map((item) => {
                return {value: item.id, key: item.name};
              }),
            );
          }}
          initialValue={this.state.schoolId === 0 ? this.state.filterSchoolId : this.state.schoolId}
          form={form}
          name="school"
          placeholder='请选择一个学校'
          getValue={(value) => {
            this.setState({schoolId: value.school})
            setTimeout(() => {
              this.searchCollage?.onSearch('');
            }, 100);
          }}
        />
      ),
    },
    {
      title: '学院',
      dataIndex: 'college',
      hideColumn: true,
      renderText: (val: string, recode: any) => (
        <span>{recode.majorInfo ? recode.majorInfo.majorName : ''}</span>
      ),
      renderFormItem: (item: any, config: any, form: any) => (
        <SearchAbleSelect
          ref={(ref: any) => this.searchCollage = ref}
          searchData={async (key) => {
            var datas: Array<any> = await APIS.OrgsAPI.SearchGetCollegeList({id: this.state.schoolId === 0 ? this.state.filterSchoolId : this.state.schoolId});
            if (datas === undefined) {
              datas = new Array<any>();
              // datas.push({id:0,key:"暂无数据"})
            }
            return Promise.resolve(
              datas.map((item) => {
                return {value: item.id, key: item.collegeName};
              }),
            );
          }}
          // initialValue={this.state.collageId}
          initialValue={this.state.collageId === 0 ? this.state.filterCollageId : this.state.collageId}
          form={form}
          name="college"
          placeholder='请选择一个学院'
          getValue={(value) => {
            this.setState({collageId: value.college})
            setTimeout(() => {
              this.searchMajor?.onSearch('');
            }, 100);
          }}
        />
      ),
    },
    {
      title: '专业',
      dataIndex: 'major',
      renderText: (val: string, recode: any) => (
        <span>{recode.majorInfo ? recode.majorInfo.majorName : ''}</span>
      ),
      renderFormItem: (item: any, config: any, form: any) => (
        <SearchAbleSelect
          ref={(ref: any) => this.searchMajor = ref}
          searchData={async (key) => {
            var datas: Array<any> = await APIS.OrgsAPI.GetCollegeMajorList({id: this.state.collageId === 0 ? this.state.filterCollageId : this.state.collageId});
            if (datas === undefined) {
              datas = new Array<any>();
            }
            return Promise.resolve(
              datas.map((item) => {
                return {value: item.id, key: item.majorName};
              }),
            );
          }}
          initialValue={this.state.majorId === 0 ? this.state.filterMajorId : this.state.majorId}
          form={form}
          name="major"
          placeholder='请选择一个专业'
        />
      ),
    },
    {
      title: '班主任',
      dataIndex: 'teacher',
      sorter: true,
      renderText: (val: string, recode: any) => (recode.teacherInfo ? recode.teacherInfo.name : ''),
      renderFormItem: (item: any, config: any, form: any) => (
        <SearchAbleSelect
          searchData={async (key) => {
            var datas: Array<any> = await APIS.OrgsAPI.SearchTeacher(key);
            return Promise.resolve(
              datas.map((item) => {
                return {value: item.id, key: item.name};
              }),
            );
          }}
          form={form}
          initialValue={form.getFieldValue("teacherInfo")?.name}
          name="teacher"
          placeholder='请选择一位老师'
        />
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'updatedTime',
      valueType: 'datetime',
      hideInForm: true,
    },
  ];

  // handleChangeFilterData(data:any) {
  //   console.log(data);
  //     }

  handleDataImport() {
  }

  handleDataExport() {
  }

  handleDelete(data: any) {
    // console.log(data);
    return APIS.OrgsAPI.DeleteClass(data.id)
      .then(() => {
        return Promise.resolve(true);
      })
      .catch(() => {
        return Promise.resolve(false);
      });
  }

  handleAdd(data: any) {
    const {filterCollageId, filterMajorId, filterSchoolId} = this.state;
    if (data.classIndex !== undefined && data.college !== undefined && data.grade !== undefined && data.major !== undefined && data.school !== undefined) {
      return APIS.OrgsAPI.CreateNewClass(data)
        .then(() => {
          return Promise.resolve(true);
        })
        .catch(() => {
          return Promise.resolve(false);
        });
    }  //filterSchoolId
    else if (filterSchoolId !== 0 && filterCollageId !== 0 && filterMajorId !== 0 && data.classIndex !== undefined && data.grade !== undefined) {
      data.college = filterCollageId;
      data.school = filterSchoolId;
      data.major = filterMajorId;
      return APIS.OrgsAPI.CreateNewClass(data)
        .then(() => {
          return Promise.resolve(true);
        })
        .catch(() => {
          return Promise.resolve(false);
        });
    } else {
      message.error({
        content: '请填写全部数据',
      })
      return Promise.resolve(false);
    }
  }

  handleUpdate(data: any) {
    if (data.classIndex !== undefined && data.college !== undefined && data.grade !== undefined && data.major !== undefined && data.school !== undefined && data.teacher !== undefined) {
      return APIS.OrgsAPI.UpdateClass(data)
        .then(() => {
          return Promise.resolve(true);
        })
        .catch(() => {
          return Promise.resolve(false);
        });
    } else {
      message.error({
        content: '请填写全部数据',
      })
      return Promise.resolve(false);
    }
  }

  requestGetData(
    params: {
      pageSize?: number;
      current?: number;
    },
    sorter: {
      [key: string]: 'ascend' | 'descend';
    },
    filter: {
      [key: string]: React.ReactText[];
    },
  ) {
    return APIS.OrgsAPI.GetClassList({
      ...params,
      sorter,
      filter,
      major: this.filterId,
      school: this.schoolId,
      college: this.collegeId
    });
  }

  handleChangeState(record: any, state: boolean) {
    return APIS.OrgsAPI.ChangeClassState({id: record.id, state: state ? 1 : 0}).then(
      (response) => {
        return Promise.resolve(response.data.state === 1);
      },
    );
  }

  // schoolId: 0,
  // filterSchoolId: 0,
  // collageId: 0,
  // filterCollageId: 0,
  // majorId: 0,
  // filterMajorId: 0,
  handleChangeFilterData(data: any) {

    this.setState({
      filterSchoolId: data[0] ? data[0] : 0,
      filterCollageId: data[1] ? data[1] : 0,
      filterMajorId: data[2] ? data[2] : 0,
    })
  }

  render() {
    return (
      <div>
        <CustomCascader datasource={[{
          placeholder: "请选择学校",
          dataGet: (values) => APIS.OrgsAPI.SearchGetSchoolList({current: 1, pageSize: 100}), renderOption: (data) => {
            return <Select.Option key={data.id} value={data.id}>{data.name}</Select.Option>
          }
        }, {
          placeholder: "请选择院系",
          dataGet: (values) => APIS.OrgsAPI.GetCollegeListBySchool({
            current: 1,
            pageSize: 100,
            id: values[0]
          }).then((res) => res.data), renderOption: (data) => {
            return <Select.Option key={data.id} value={data.id}>{data.collegeName}</Select.Option>
          }
        }, {
          placeholder: "请选择专业",
          dataGet: (values) => APIS.OrgsAPI.GetCollegeMajorList({id: values[1]}), renderOption: (data) => {
            return <Select.Option key={data.id} value={data.id}>{data.majorName}</Select.Option>
          }
        }]} onChange={(values) => {
          this.handleChangeFilter(values)
          this.handleChangeFilterData(values);
        }}></CustomCascader>
        <HighPerformTable<any>
          requestGetData={this.requestGetData.bind(this)}
          ref={(ref) => (this.actionRef = ref)}
          columns={this.clomns}
          handleDelete={this.handleDelete.bind(this)}
          handleAdd={this.handleAdd.bind(this)}
          handleChangeState={this.handleChangeState.bind(this)}
          handleUpdate={this.handleUpdate.bind(this)}
          onClickUpdate={record => {
            this.setState({
              schoolId: record.majorInfo.collegeData.schoolInfo.id,
              collageId: record.majorInfo.collegeData.id,
              majorId: record.majorInfo.id
            })
            this.actionRef.handleUpdateModalVisible(true, record)
          }}
          // additionOptions={[
          //   {
          //     title: '查看',
          //     onClick: (record: any) => {
          //       this.props.history.push('/teaching/classD');
          //     },
          //   },
          // ]}
          toolBarRender={() => [
            <Button type="primary" onClick={() => {
              this.setState({schoolId: 0, collageId: 0, majorId: 0});
              this.actionRef.handleModalVisible(true)
            }}>
              <PlusOutlined/> 新增班级
            </Button>,
          ]}
        />
      </div>
    );
  }
}

export default connect()(ClassManagerPage);
